package com.maimang.platform.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.shiro.codec.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Calendar;
import java.util.Date;

/**
 * jwt生成工具类
 *
 * @author Rocky
 * @create 2019-01-08
 */
public class JwtUtils {
	private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
	private static final String SECRET = "ILoveYouLikeMiceLoveRice";
	private static final String ISSUER = "Rocky";

	/**
	 * 生成token
	 *
	 * @param infoJson token包含的信息,建议转成Json字符串存入
	 * @param second   token有效时长(秒)
	 * @return 返回生成的token字符串
	 */
	public static String createToken(String infoJson, int second) throws Exception {
		try {
			Algorithm algorithm = Algorithm.HMAC256(SECRET);
			JWTCreator.Builder builder = JWT.create()
					.withIssuer(ISSUER)
					.withExpiresAt(DateUtils.addSeconds(new Date(), second))
					.withSubject(infoJson);
			return builder.sign(algorithm);
		} catch (IllegalArgumentException e) {
			logger.error("生成token失败", e);
			throw new Exception("生成token失败");
		}
	}

	/**
	 * 验证jwt，并返回数据
	 *
	 * @param token
	 * @return 失败返回null
	 * @throws Exception
	 */
	public static String verifyToken(String token) throws Exception {
		Algorithm algorithm;
		String re = null;
		try {
			algorithm = Algorithm.HMAC256(SECRET);
			JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
			DecodedJWT jwt = verifier.verify(token);
			re = jwt.getSubject();
		} catch (Exception e) {
			logger.info("鉴权失败", e);
		}
		return re;
	}

	/**
	 * 获得token的到期时间
	 *
	 * @return token中包含的签发时间
	 */
	public static Date getIssuedAt(String token) {
		try {
			Algorithm algorithm = Algorithm.HMAC256(SECRET);
			JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
			DecodedJWT jwt = verifier.verify(token);
			return jwt.getExpiresAt();
		} catch (Exception e) {
			logger.error("获取有效时间失败", e);
			return null;
		}
	}

	/**
	 * 获得token的到期剩余时间 毫秒
	 *
	 * @return token中包含的签发时间
	 */
	public static long getLiveTime(String token) {
		try {
			Date date = getIssuedAt(token);
			if (date != null) {
				return (date.getTime() - new Date().getTime());
			}
		} catch (Exception e) {
			logger.error("获取剩余有效时间失败", e);
			return 0;
		}
		return 0;
	}


	/**
	 * token是否过期
	 *
	 * @return true：过期
	 */
	public static boolean isTokenExpired(String token) {
		Date now = Calendar.getInstance().getTime();
		Date issuedAt = getIssuedAt(token);
		return issuedAt == null || issuedAt.before(now);
	}

	public static void main(String[] ss) throws Exception {
       // String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIiwiaXNzIjoiUm9ja3kiLCJleHAiOjE1Njg2ODgwOTl9.DIDwOO5VfW4JfzF0OFLKz68_P4tYJ-F_ZBZobX8Jgqg";
       // String verifyToken = verifyToken(token);
       // System.out.println(verifyToken);
		KeyGenerator keygen = KeyGenerator.getInstance("AES");
		SecretKey deskey = keygen.generateKey();
		System.out.println(deskey.getFormat());
		System.out.println(Base64.encodeToString(deskey.getEncoded()));
       // SysUser sysUser = new JSONObject(verifyToken);
       // System.out.println(sysUser.getRoles().get(0).getRoleName());
		String newToken = createToken("1", 6000);
		System.out.println(newToken);

	}
}
